package com.hmdp.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

/**
 * id生成器
 */
@Component
public class RedisIdWorker {

    /**
     * 开始的时间戳
     */
    private static final long BEGIN_TIMESTAMP = 1722470400L;
    /**
     * 时间戳移位的长度
     */
    private static final int COUNT_BITS = 32;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public long nextId(String kePrefix) {
        //1.生成时间戳（当前时间-开始时间）
        LocalDateTime now = LocalDateTime.now();
        long nowSecond = now.toEpochSecond(ZoneOffset.UTC);
        long timestamp = nowSecond - BEGIN_TIMESTAMP;

        //2.生成序列号
        //2.1 获取当前的日期，精确到天，因为你这个key不能一直增长
        String date = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd")); //一天一个key
        //2.2 自增
        Long count = stringRedisTemplate.opsForValue().increment("icr:" + kePrefix + ":" + date);

        //3.拼接，返回
        return timestamp << COUNT_BITS | count;
    }

    //计算指定时间的时间戳
    /*public static void main(String[] args) {
        LocalDateTime time = LocalDateTime.of(2024, 8, 1, 0, 0, 0);
        long second = time.toEpochSecond(ZoneOffset.UTC);
        System.out.println("second = " + second);
    }*/
}
